<template>
  <div>

    <div style="text-align:left" v-if="searchFlg">
      <el-form :inline="true" :model="like" class="demo-form-inline">
        <el-form-item label="菜单名称" style="font-weight: bold">
          <el-input v-model="like.menuName" placeholder="菜单名称" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="font-weight: bold">
          <el-select v-model="like.status" prop="status" size="mini">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getMenuList" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作列表 -->
    <el-row style="margin-bottom:10px">
      <el-col :span="12" style="text-align:left">
        <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="clickDialog('insert')">新增</el-button>
        <el-button type="info" icon="el-icon-sort" @click="UnfoldOrFold()" size="mini">展开/折叠</el-button>
      </el-col>
      <el-col :span="12" style="text-align:right">
        <el-tooltip class="item" effect="dark" :content="searchFlg ? '隐藏搜索' : '展开搜索'" placement="top">
          <el-button icon="el-icon-search" size="mini" circle @click="searchFlg = !searchFlg"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button icon="el-icon-refresh" size="mini" circle @click="getMenuList"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 菜单列表 -->
    <el-table v-if="refreshTable" :data="tableData" style="width: 100%" row-key="meta.id"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children' }" v-loading="loading"
      :header-cell-style="{ background: '#F5F7FA', 'font-weight': '800', 'color': '#606266' }">
      <el-table-column prop="meta.title" label="菜单名称" width="200">
      </el-table-column>
      <el-table-column prop="meta.icon" label="图标" width="55">
        <template slot-scope="scope">
          <i :class="scope.row.meta.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="meta.sort" label="排序" width="55">
      </el-table-column>
      <el-table-column prop="meta.perms" label="权限标识" width="300">
      </el-table-column>
      <el-table-column prop="path" label="地址路由" width="220">
      </el-table-column>
      <el-table-column prop="component" label="组件路径" width="390">
      </el-table-column>
      <el-table-column prop="meta.status" label="状态" width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.meta.status == 0 ? 'success' : 'danger'" disable-transitions>{{ scope.row.meta.status
            == 0 ? "正常" : "停用" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template slot-scope="scope">
          <!-- {{ scope.row.meta.createDate | formatDate }} -->
          {{ formatDate(scope.row.meta.createDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="215">
        <template slot-scope="scope">
          <button type="button" @click="clickDialog('update', scope.row.meta.id)"
            class="el-button el-button--text el-button--mini" style="width: 35px;" v-show="scope.row.meta.status == 0">
            <i class="el-icon-edit">
              <span>修改</span>
            </i>
          </button>

          <button type="button" @click="clickDialog('insert', scope.row.meta.id, scope.row.meta.title)"
            class="el-button el-button--text el-button--mini" style="width: 35px;" v-show="scope.row.meta.status == 0">
            <i class="el-icon-edit">
              <span>增加</span>
            </i>
          </button>

          <button type="button" @click="clickDelete(scope.row.meta.id, scope.row.meta.status)"
            class="el-button el-button--text el-button--mini" style="width: 60px;">
            <i class="el-icon-edit" v-show="scope.row.meta.status == 0">
              <span>删除</span>
            </i>
            <i class="el-icon-edit" v-show="scope.row.meta.status == 1">
              <span>彻底删除</span>
            </i>
          </button>

          <button type="button" @click="clickDelete(scope.row.meta.id, 'recover')"
            class="el-button el-button--text el-button--mini" style="width: 35px;">
            <i class="el-icon-edit" v-show="scope.row.meta.status == 1">
              <span>恢复</span>
            </i>
          </button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增模块 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :append-to-body="true">
      <el-form :model="menu" :rules="rules" ref="menu" label-width="80px">

        <el-form-item label="上级菜单">
          <el-select v-model="treeContext" clearable placeholder="主菜单" @clear="handleClear" ref="selectBlur" size="small"
            style="width: 100%;">
            <el-option hidden key="upResId" :value="menu.parentId" :label="treeContext">
            </el-option>
            <el-tree :data="tableData" :props="defaultProps" :expand-on-click-node="false" :check-on-click-node="true"
              @node-click="handleNodeClick">
            </el-tree>
          </el-select>

        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menu.type">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单图标" prop="icon" v-show="menu.type == 'M' || menu.type == 'C'">
          <el-select v-model="menu.icon" filterable clearable placeholder="请选择" size="small"
            style="width:100%;display: flex;flex-flow: wrap;">
            <el-option v-for="item in iconList" :key="item" :label="item" :value="item">
              <span>
                <i :class="item"></i> <!-- 如果动态显示图标，这里添加判断 -->
              </span>
              <span style="padding-left: 3px;">{{ item }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" required prop="menuName">
              <el-input v-model="menu.menuName" size="small" placeholder="请输入菜单名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input-number v-model="menu.sort" size="small" :min="1" :max="100"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="menu.type == 'M' || menu.type == 'C'">
          <el-col :span="12">
            <el-form-item label="地址路由" prop="path">
              <el-input v-model="menu.path" placeholder="请输入路由地址" size="small"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-show="menu.type == 'C'">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="menu.component" placeholder="请输入组件路径" size="small"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-show="menu.type == 'C' || menu.type == 'F'">
            <el-form-item label="权限字符" prop="perms">
              <el-input v-model="menu.perms" placeholder="请输入权限字符" size="small"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('menu')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增模块 -->
  </div>
</template>

<script>
import { elementIcons } from '@/util/icon/icon'

export default {
  name: "menuIndex",
  data() {
    return {
      loading: true,
      tableData: [],
      like: {
        menuName: "",//模糊查询值
        status: "0",//模糊查询值
      },
      isExpandAll: false,//是否全部展开 默认全部折叠flg
      refreshTable: true, //重新渲染表格的状态
      dialogVisible: false,//打开新增模态框flg
      searchFlg: true,//搜索框展示/隐藏flg
      dialogTitle: "",
      treeContext: "",//下拉tree框展示内容
      iconList: [],
      //表单数据
      menu: {
        id: "",
        parentId: 0,
        type: "M",
        icon: "",
        menuName: "",//菜单名
        sort: "1",
        path: "",
        component: "",
        perms: "",
      },
      //下拉tree渲染展示
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //表单校验规则
      rules: {
        //菜单名称
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: 'blur' },
          { min: 2, max: 18, message: '长度在 2 到 40 个字符', trigger: 'blur' }
        ],
        // path: [
        //   { required: true, message: "请输入路由地址", trigger: 'blur' },
        //   { min: 2, max: 18, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        // ]

      }
    }
  },
  created() {
    this.getMenuList()
    this.iconList = elementIcons
  },
  methods: {
    UnfoldOrFold() {
      //点击折叠或者打开
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => { //在数据加载完，重新渲染表格 
        this.refreshTable = true;
      });
    },
    handleNodeClick(data) {
      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.menu.parentId = data.meta.id // id
      this.treeContext = data.meta.title // 显示的信息
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectBlur.blur()
    },
    clickDialog(op, id, title) {
      //点击按钮显示会话框（新增、修改）
      if (op == 'insert') {
        if (this.dialogTitle == '修改菜单') {
          this.reset()
        }
        this.dialogTitle = "新增菜单"
        if (id != undefined) {
          //代表当前是新增操作，并且点击的是行中的新增，就显示当前菜单为上级菜单
          this.menu.parentId = id
          this.treeContext = title
        }
      } else if (op == 'update') {
        this.dialogTitle = "修改菜单"
        this.selectMenuById(id, true)
      }
      this.dialogVisible = true
    },
    clickDelete(id, status) {
      let content = "";
      if (status == 'recover') {
        content = "是否确认恢复？"
      } else {
        content = status == 0 ? '是否确认删除?' : '删除后将不可恢复，谨慎操作！！！'
      }

      this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteMenu(id, status)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },



    //表单操作：新增、修改
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          //true:添加菜单 false修改菜单
          if (this.menu.id == "") {
            this.insertMenu()
          } else {
            this.updateMenu()
          }
        } else {
          return false;
        }
      })
    },

    // 表单重置
    reset() {
      this.menu = {
        id: "",
        parentId: 0,
        type: "M",
        icon: "",
        menuName: "",
        sort: "1",
        path: "",
        component: "",
        perms: "",
      };
      this.handleClear()
      this.$refs['menu'].resetFields();
    },
    handleClear() {
      // 将选择器的值置空
      this.menu.parentId = 0
      this.treeContext = ''
    },
    //给icon绑定的点击事件
    setIcon(icon) {
      this.menu.icon = icon;//将i的样式设为选中的样式el-icon-xxx
    },

    //查询菜单列表
    getMenuList() {
      this.loading = true
      let map = {
        "menuName": this.like.menuName,
        "status": this.like.status
      }
      this.$axios.post("/menu/getMenusList", map).then(res => {
        this.tableData = res.data.data
        this.loading = false
      })
    },
    //通过菜单id查询
    selectMenuById(id, flg) {
      this.$axios.get("/menu/selectMenuById?id=" + id).then(res => {
        let data = res.data.data
        if (flg) {
          this.menu.id = data.id
          this.menu.parentId = data.parentId
          this.menu.type = data.type
          this.menu.icon = data.icon
          this.menu.menuName = data.menuName
          this.menu.sort = data.sort
          this.menu.path = data.path
          this.menu.component = data.component
          this.menu.perms = data.perms
          if (data.parentId == 0) {
            this.treeContext = data.menuName
          } else {
            this.selectMenuById(data.parentId, false)
          }
        } else {
          this.treeContext = data.menuName
        }
      })
    },
    //新增菜单
    insertMenu() {
      let then = this
      this.$axios.post("/menu/addMenu", this.menu).then(function () {
        then.getMenuList()
        then.reset()
      })
    },
    //修改菜单
    updateMenu() {
      let then = this
      this.$axios.put("/menu/updateMenu", this.menu).then(function () {
        then.getMenuList()
        then.reset()
        then.getRouter()
      })
    },
    //删除菜单
    deleteMenu(id, status) {
      let then = this

      if (status == "1") {
        //彻底删除
        this.$axios.delete("/menu/completelyDeleteMenu?id=" + id).then(function () {
          then.getMenuList()
          then.getRouter()
        })
      } else if (status == "0") {
        //修改菜单显示状态
        let data = {
          id: id,
          status: 1
        }
        this.$axios.delete("/menu/deleteMenu", { data: data }).then(function () {
          then.getMenuList()
          then.getRouter()
        })
      } else if (status == "recover") {
        let newMenu = {
          id: id,
          status: 0
        }
        this.recoverMenu(newMenu);
      }

    },
    //恢复菜单
    recoverMenu(data) {
      let then = this
      this.$axios.put("/menu/recoverMenu", data).then(function () {
        then.getMenuList()
      })
    },

    //查询侧边栏列表
    getRouter() {
      let then = this
      this.$axios.get("/menu/getMenus").then(res => {
        then.$store.commit("SET_ROUTERS", res.data.data)
      })
    }
  },
}
</script>

<style scoped>
.el-form-item__label {
  font-weight: bold;
}
</style>
